package com.gooseeker.mbus;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.gooseeker.modbus.ConstValue;
import com.gooseeker.modbus.DataAnalysis;
import com.gooseeker.modbus.bean.SensorResultBean;
import com.gooseeker.modbus.bean.StationInfoBean;
import com.gooseeker.util.Constants;
/**
 * 解析线程，解析消息
 * @author ysite
 *
 */
public class ParseFrameThread implements Runnable {
	private Logger logger = Logger.getLogger(ParseFrameThread.class);
	
	private byte[] frame = new byte[Constants.DEFAULT_RECV_BUFFER_SIZE];
	public ParseFrameThread(byte[] data)
	{
		System.arraycopy(data, 0, frame, 0, Constants.DEFAULT_RECV_BUFFER_SIZE);
	}
	@Override
	public void run() {
		List<SensorResultBean> resultList = DataAnalysis.parseDataram(frame);
		logger.debug("parse frame ,resultList="+resultList.size());
		for (int i = 0; i < resultList.size(); i++)
		{
			SensorResultBean bean = resultList.get(i);
			// 用于缓存当前数据
			SensorResultBean resultBean = new SensorResultBean(bean);
			StationInfoBean infoBean = new StationInfoBean();
			infoBean.setAddress(bean.getDeviceAddr());
			infoBean.setSubAddress(bean.getSensorAddr());
			infoBean.setCreateTime(System.currentTimeMillis());
			
			List<SensorResultBean> tempBeanList = Constants.DATA_MAP.get(infoBean);
			if(null == tempBeanList)
			{
				tempBeanList = new ArrayList<SensorResultBean>();
				Constants.DATA_MAP.put(infoBean, tempBeanList);
			}
			
			if (tempBeanList.size() < Constants.CMD_RESEND_TIMES)
			{
				// 如果已存在数据，则向list中再插入数据，插入个数由配置文件决定
				tempBeanList.add(resultBean);
				
				logger.debug("add resultBean to List ,tempBeanList="+tempBeanList.size());
				
				if(tempBeanList.size() >= Constants.CMD_RESEND_TIMES)
				{
					logger.info("deal data . tempBeanList="+tempBeanList.size());
					//保存数据到数据库
					SensorResultBean result = tempBeanList.get(0);
					short line1 = 0;
					short line2 = 0;
					for(int j = 0; j < tempBeanList.size(); j++)
					{
						line1 += tempBeanList.get(j).getValue1();
						line2 += tempBeanList.get(j).getValue2();
					}
					
					line1 = (short)(line1 / tempBeanList.size());
					line2 = (short)(line2 / tempBeanList.size());
					result.setValue1(line1);
					result.setValue2(line2);
					if (line1 < Constants.UNUSE_RESULT_DELTA && line2 < Constants.UNUSE_RESULT_DELTA)
					{
						result.setState(ConstValue.SENSOR_STATUS_UNUSE);
					}
					else if (line1 >= Constants.PASS_ADC_THRESHOLD_VALUE && line2 <= Constants.UNUSE_RESULT_DELTA)
					{
						result.setState(ConstValue.SENSOR_STATUS_PASS);
					}
					else
					{
						result.setState(ConstValue.SENSOR_STATUS_FAIL);
					}
					logger.debug("insert to DB for result ,infoBean="+infoBean.getAddress()+" , "+infoBean.getSubAddress());
					//入库
					Modbus.getInstance().insertToDB(infoBean, result);
					//删除MAP
					Constants.DATA_MAP.remove(infoBean);
				}
			}
		}
	}
}
